package srpingmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class UploadController {

    @RequestMapping("/upload")
    public void upload(@RequestParam("picture") MultipartFile picture) throws Exception {
        System.out.println(picture.getOriginalFilename());

    }

    @RequestMapping("/uploadImage")
    public ModelAndView upload(HttpServletRequest request, @RequestParam(value="picture",required=false) MultipartFile file)
            throws IllegalStateException, IOException {
        System.out.println(file.getOriginalFilename());
//        String name = RandomStringUtils.randomAlphanumeric(10);
        int i = (int) (Math.random() * 100 + 100);
        String name = i + "";
        String newFileName = name + ".jpg";
        System.out.println(newFileName);
        File newFile = new File(request.getServletContext().getRealPath("/image"), newFileName);
        newFile.getParentFile().mkdirs();
        System.out.println(newFile);
            //io包冲突，
//        file.transferTo(newFile);

        ModelAndView mav = new ModelAndView("showimagefile");
        mav.addObject("imageName", newFileName);
        return mav;
    }

    @RequestMapping("/test2")
    public ModelAndView upload() {
        return new ModelAndView("upload");
    }

}
